package com.wmh.baseservice.skd.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wmh.baseservice.common.redis.utils.RedisUtil;
import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.PathUtil;
import com.wmh.baseservice.common.utils.QrCodeUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.utils.upload.service.CosService;
import com.wmh.baseservice.merchant.pojo.MerchantGroupGoods;
import com.wmh.baseservice.merchant.pojo.dto.GroupGoodsDTO;
import com.wmh.baseservice.skd.pojo.SkdGroupBuyingActivities;
import com.wmh.baseservice.skd.pojo.SkdGroupBuyingServiceCommitment;
import com.wmh.baseservice.skd.pojo.SkdWechatFanCard;
import com.wmh.baseservice.skd.pojo.dto.NearbyPickupPointDTO;
import com.wmh.baseservice.skd.pojo.vo.*;
import com.wmh.baseservice.merchant.service.MerchantGroupGoodsService;
import com.wmh.baseservice.skd.pojo.SkdLeaderInfo;
import com.wmh.baseservice.skd.service.*;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.vo.SalesDataRespVO;
import com.wmh.baseservice.user.pojo.vo.UsInfoRespVO;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.error;
import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;
import static com.wmh.baseservice.skd.utils.VerifyGroupBuyingActivityParams.*;

@Api(tags = "团购商品相关接口")
@Validated
@RestController
@RequestMapping(value = "group-buy", produces = "text/plain;charset=utf-8")
@Slf4j
public class GroupBuyController {
    @Resource
    private TokenService tokenService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private SkdGoodsInfoService skdGoodsInfoService;
    @Resource
    private SkdLeaderInfoService skdLeaderInfoService;
    @Resource
    private SkdCommissionsAndRewardsService skdCommissionsAndRewardsService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private SkdWechatFanCardService skdWechatFanCardService;
    @Resource
    private SkdPickupPointService skdPickupPointService;
    @Resource
    private SkdGroupBuyingActivitiesService skdGroupBuyingActivitiesService;
    @Resource
    private SkdGroupBuyingServiceCommitmentService skdGroupBuyingServiceCommitmentService;
    @Resource
    private CosService cosService;

    /**
     * #0001 设置首页海报
     * @return 返回图片key
     */
    @ApiOperation("上传首页海报")
    @PostMapping("homepage-poster")
    public String setHomepagePoster(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return error("未提交图片文件");
        }
        // 生成海报唯一文件名
        String homepagePosterUniqueFileName = CommUtil.generateUniqueFileName(Objects.requireNonNull(file.getOriginalFilename()));
        String suffix = homepagePosterUniqueFileName.substring(homepagePosterUniqueFileName.lastIndexOf("."));
        //判断文件格式是否支持
        if (!".jpg,.jpeg,.png,.gif".contains(suffix.trim().toLowerCase())) {
            return error("图片格式不支持");
        }
        String upload = cosService.upload(file.getBytes(), "homepage_poster/" + homepagePosterUniqueFileName);
        if(!"error".equals(upload)) {
            log.info("首页海报上传成功!");
            // 将首页海报key存入redis
            redisUtil.set("homepage_poster", upload);
            return success(upload);
        } else {
            log.info("首页海报上传失败!");
            return error("首页海报上传失败!");
        }
    }

    /**
     * #0002 获取首页海报
     * @return 返回图片url
     */
    @ApiOperation("获取首页海报")
    @GetMapping("homepage-poster")
    public String getHomepagePoster() {
        Object key = redisUtil.get("homepage_poster");
        return ReturnBody.success(PathUtil.COS_DOMAIN + key);
    }

    /**
     * #0003 获取附近团购
     * @param lat String 维度
     * @param lng String 经度
     * @return Array 团购对象数组, 包含一个商品图片和商品主id
     */
    @ApiOperation("获取附近团购")
    @GetMapping("nearby")
    public String getNearbyGroupBuys(@NotBlank(message = "未提交纬度") String lat,
                                     @NotBlank(message = "未提交经度") String lng) {
        // 根据经纬度获取附近三公里内的自提点
        List<NearbyPickupPointDTO> pickupPointsAndDistance = skdPickupPointService.getNearbyPickupPoints(lat, lng);

        List<Map<Long, Double>> pickupPointsAndDistanceList = new ArrayList<>();

        pickupPointsAndDistance.forEach(i -> {
            HashMap<Long, Double> map = new HashMap<>();
            map.put(i.getId(), i.getDistance());
            pickupPointsAndDistanceList.add(map);
        });

        // 获取附近团购活动并按距离排序
        List<NearbyGroupBuyingActiviesRespVO> nearbyGroupBuyingActiviesRespVOList = skdGroupBuyingActivitiesService.getNearbyGroupBuys(pickupPointsAndDistanceList);

        // 对列表进行距离排序
        nearbyGroupBuyingActiviesRespVOList.sort(Comparator.comparingDouble(NearbyGroupBuyingActiviesRespVO::getDistance));

        return ReturnBody.success(nearbyGroupBuyingActiviesRespVOList);
    }

    /**
     * #0006 团购热卖好货
     * @return {@link GroupGoodsHotDealRespVO} 返回长度为4的团购商品对象数组
     */
    @ApiOperation("团购热卖好货")
    @GetMapping("hot-deals")
    public String getGroupBuyingHotDeals() {
        List<GroupGoodsHotDealRespVO> hotDealRespVOList = new ArrayList<>();

        List<SkdLeaderInfo> skdLeaderInfoList = skdLeaderInfoService.querySkdLeaderInfoByFollowGroupNumDesc();
        for (SkdLeaderInfo skdLeaderInfo : skdLeaderInfoList) {

            GroupGoodsHotDealRespVO groupGoodsHotDealRespVO = new GroupGoodsHotDealRespVO();

            SkdGroupBuyingActivities skdGroupBuyingActivities = skdGroupBuyingActivitiesService.getById(skdLeaderInfo.getGroupBuyingActivityId());
            log.info("skdLeaderInfo" + skdLeaderInfo);
            groupGoodsHotDealRespVO.setFollowGroupNum(skdLeaderInfo.getFollowGroupNum());

            String priceRange = skdGroupBuyingActivitiesService.getPriceRangeFromGoodsSnapshot((skdGroupBuyingActivities.getGoodsSnapshot()));
            List<String> goodsImages = skdGroupBuyingActivitiesService.getGoodsImagesFromGoodsSnapshot((skdGroupBuyingActivities.getGoodsSnapshot()));
            groupGoodsHotDealRespVO.setPriceRange(priceRange);
            groupGoodsHotDealRespVO.setGoodsImage(goodsImages.get(0));

            hotDealRespVOList.add(groupGoodsHotDealRespVO);
        }
        return ReturnBody.success(hotDealRespVOList);
    }

    /**
     * #0009 获取销售数据
     * @return 返回销售数据
     */
    @ApiOperation("获取销售数据")
    @GetMapping("sales-data")
    public String getSalesData() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        SalesDataRespVO respVO = new SalesDataRespVO();
        // 总访客
        int totalVisitors = 0;
        // 总收入
        BigDecimal totalRevenue = new BigDecimal(0);
        // 团长跟团号列表
        List<Long> groupNoList = new ArrayList<>();

        List<SkdLeaderInfo> skdLeaderInfoList = skdLeaderInfoService.getLeaderInfoListByUsId(usId);
        for (SkdLeaderInfo skdLeaderInfo : skdLeaderInfoList) {
            totalVisitors += skdLeaderInfo.getBrowseNum();
            totalRevenue = totalRevenue.add(skdCommissionsAndRewardsService.getTotalAmountByLeaderId(skdLeaderInfo.getId()));
            groupNoList.add(skdLeaderInfo.getGroupNo());
        }
        // 获取销售中和已下架的商品数量
        Map<Integer, Integer> res = skdGoodsInfoService.countGoodsOffShelvesByUserId(usId);
        respVO.setSale(res.get(0));
        respVO.setOffShelves(res.get(1));
        respVO.setTotalRevenue(totalRevenue);
        // 根据团长团号列表查询团长订单总数
        int totalOrder = usGroupGoodsOrderService.getLeaderTotalOrderNumByGroupNoList(groupNoList);
        respVO.setTotalOrder(totalOrder);
        respVO.setTotalVisitors(totalVisitors);
        return ReturnBody.success(respVO);
    }

    /**
     * #0036 添加团购承诺
     * @return 返回是否添加成功信息
     */
    @ApiOperation("添加团购承诺")
    @PostMapping("service-commitments")
    public String addGroupBuyingServiceCommitment(AddServiceCommitmentReqVO reqVO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        // 检查所有字段是否为空
        boolean allFieldsEmpty = Stream.of(reqVO.getTitle(), reqVO.getShippingArea(), reqVO.getShippingExpress(),
                        reqVO.getShippingTime(), reqVO.getAfterSalesStandards(), reqVO.getServiceDetails())
                .allMatch(StringUtils::isBlank);

        if (allFieldsEmpty) {
            return ReturnBody.error("所有字段均为空，请至少提供一个字段的数据!");
        }
        SkdGroupBuyingServiceCommitment skdGroupBuyingServiceCommitment = new SkdGroupBuyingServiceCommitment();
        skdGroupBuyingServiceCommitment
                .setUserId(usId)
                .setTitle(reqVO.getTitle())
                .setShippingArea(reqVO.getShippingArea())
                .setShippingExpress(reqVO.getShippingExpress())
                .setShippingTime(reqVO.getShippingTime())
                .setAfterSalesStandards(reqVO.getAfterSalesStandards())
                .setServiceDetails(reqVO.getServiceDetails());
        skdGroupBuyingServiceCommitmentService.save(skdGroupBuyingServiceCommitment);
        return ReturnBody.success("添加成功!");
    }

    /**
     * #0037 删除团购承诺
     * @param serviceCommitmentId 团购承诺id
     * @return 返回是否删除成功信息
     */
    @ApiOperation("删除团购承诺")
    @DeleteMapping("service-commitments")
    public String deleteServiceCommitment(@NotNull(message = "未提交团购承诺id") Long serviceCommitmentId) {
        SkdGroupBuyingServiceCommitment res = skdGroupBuyingServiceCommitmentService.getById(serviceCommitmentId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该团购承诺不存在!");
        }
        skdGroupBuyingServiceCommitmentService.removeById(serviceCommitmentId);
        return ReturnBody.success("删除成功!");
    }

    /**
     * #0038 修改团购承诺
     * @return 返回是否修改成功信息
     */
    @ApiOperation("修改团购承诺")
    @PutMapping("service-commitments")
    public String modifyServiceCommitment(@Valid ModifyServiceCommitmentReqVO reqVO) {
        SkdGroupBuyingServiceCommitment res = skdGroupBuyingServiceCommitmentService.getById(reqVO.getServiceCommitmentId());
        if (Objects.isNull(res)) {
            return ReturnBody.error("该团购服务承诺不存在!");
        }

        UpdateWrapper<SkdGroupBuyingServiceCommitment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", reqVO.getServiceCommitmentId());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getTitle()), "title", reqVO.getTitle());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getShippingTime()), "shipping_time", reqVO.getShippingTime());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getShippingArea()), "shipping_area", reqVO.getShippingArea());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getShippingExpress()), "shipping_express", reqVO.getShippingExpress());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getAfterSalesStandards()), "after_sales_standards", reqVO.getAfterSalesStandards());
        updateWrapper.set(StrUtil.isNotBlank(reqVO.getServiceDetails()), "service_details", reqVO.getServiceDetails());

        boolean updateResult = skdGroupBuyingServiceCommitmentService.update(updateWrapper);
        if (updateResult) {
            return ReturnBody.success("修改成功!");
        } else {
            return ReturnBody.error("修改失败!");
        }
    }

    /**
     * #0039 查询团购承诺
     * @return 返回团购承诺列表
     */
    @ApiOperation("查询团购承诺")
    @GetMapping("service-commitments")
    public String queryServiceCommitment() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        List<SkdGroupBuyingServiceCommitment> skdGroupBuyingServiceCommitmentList = skdGroupBuyingServiceCommitmentService.list(new QueryWrapper<SkdGroupBuyingServiceCommitment>().eq("user_id", usId));
        List<ServiceCommitmentRespVO> serviceCommitmentRespVOList = skdGroupBuyingServiceCommitmentList.stream().map(serviceCommitment -> {
            ServiceCommitmentRespVO respVO = new ServiceCommitmentRespVO();
            respVO.setServiceCommitmentId(serviceCommitment.getId())
                    .setTitle(serviceCommitment.getTitle())
                    .setShippingTime(serviceCommitment.getShippingTime())
                    .setShippingArea(serviceCommitment.getShippingArea())
                    .setShippingExpress(serviceCommitment.getShippingExpress())
                    .setAfterSalesStandards(serviceCommitment.getAfterSalesStandards())
                    .setServiceDetails(serviceCommitment.getServiceDetails());
            return respVO;
        }).collect(Collectors.toList());
        return ReturnBody.success(serviceCommitmentRespVOList);
    }


    /**
     * #0040 查看图片是否为二维码图片
     * @return 返回图片是否为二维码
     */
    @ApiOperation("查看图片是否为二维码图片")
    @PostMapping("check-qrcode")
    public String checkQRCode(@NotNull(message = "未提交二维码图片") MultipartFile file) {
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            boolean isQRCode = QrCodeUtil.isQRCodeImage(bufferedImage);
            if (isQRCode) {
                return ReturnBody.success(true);
            } else {
                return ReturnBody.error(false);
            }
        } catch (IOException e) {
            return ReturnBody.error("文件读取错误");
        }
    }

    /**
     * #0041 添加微信加粉卡片
     * @return 返回是否添加成功信息
     */
    @ApiOperation("添加微信加粉卡片")
    @PostMapping("wechat-fan-card")
    public String addWechatFanCard(@NotBlank(message = "未提交微信昵称") String nick,
                                   @NotBlank(message = "未提交二维码图片地址") String qrCodeImageUrl,
                                   String guideAttentionWords) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        SkdWechatFanCard skdWechatFanCard = new SkdWechatFanCard();
        skdWechatFanCard.setUserId(usId).setNick(nick).setQrCodeImageUrl(qrCodeImageUrl);
        if (StrUtil.isBlank(guideAttentionWords)) {
            skdWechatFanCard.setGuideAttentionWords("添加我的微信，直接联系我");
        } else {
            skdWechatFanCard.setGuideAttentionWords(guideAttentionWords);
        }
        skdWechatFanCardService.save(skdWechatFanCard);
        return ReturnBody.success("添加成功!");
    }

    /**
     * #0042 删除微信加粉卡片
     * @return 返回是否删除成功信息
     */
    @ApiOperation("删除微信加粉卡片")
    @DeleteMapping("wechat-fan-card")
    public String deleteWechatFanCard(@NotNull(message = "未提交微信加粉卡片id") Long wechatFanCardId) {
        SkdWechatFanCard res = skdWechatFanCardService.getById(wechatFanCardId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该微信加粉卡片不存在!");
        }
        skdWechatFanCardService.removeById(wechatFanCardId);
        return ReturnBody.success("删除成功!");
    }

    /**
     * #0043 修改微信加粉卡片
     * @return 返回是否修改成功信息
     */
    @ApiOperation("修改微信加粉卡片")
    @PutMapping("wechat-fan-card")
    public String modifyWechatFanCard(@NotNull(message = "未提交微信加粉卡片id") Long wechatFanCardId, String nick, String qrCodeImageUrl, String guideAttentionWords) {
        SkdWechatFanCard res = skdWechatFanCardService.getById(wechatFanCardId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该微信加粉卡片不存在!");
        }

        UpdateWrapper<SkdWechatFanCard> updateWrapper = new UpdateWrapper<SkdWechatFanCard>()
                .eq("id", wechatFanCardId);

        updateWrapper.set(StrUtil.isNotBlank(nick), "nick", nick);
        updateWrapper.set(StrUtil.isNotBlank(qrCodeImageUrl), "qr_code_image_url", qrCodeImageUrl);
        updateWrapper.set(StrUtil.isNotBlank(guideAttentionWords), "guide_attention_words", guideAttentionWords);

        boolean updateResult = skdWechatFanCardService.update(updateWrapper);
        if (updateResult) {
            return ReturnBody.success("修改成功!");
        } else {
            return ReturnBody.error("修改失败!");
        }
    }

    /**
     * #0044 查询微信加粉卡片
     * @return 返回微信加粉卡片列表
     */
    @ApiOperation("查询微信加粉卡片")
    @GetMapping("wechat-fan-card")
    public String queryWechatFanCard() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        List<SkdWechatFanCard> skdWechatFanCardList = skdWechatFanCardService.list(new QueryWrapper<SkdWechatFanCard>().eq("user_id", usId));
        List<WechatFanCardResqVO> wechatFanCardResqVOList = skdWechatFanCardList.stream().map(fanCard -> {
            WechatFanCardResqVO respVO = new WechatFanCardResqVO();
            respVO.setWechatFanCardId(fanCard.getId())
                    .setNick(fanCard.getNick())
                    .setQrCodeImageUrl(fanCard.getQrCodeImageUrl())
                    .setGuideAttentionWords(fanCard.getGuideAttentionWords());
            return respVO;
        }).collect(Collectors.toList());

        return ReturnBody.success(wechatFanCardResqVOList);
    }

    /**
     * #0045 一键开团
     * @return 返回是否开团成功信息
     */
    @ApiOperation("一键开团")
    @PostMapping
    public String startGroupBuying(@Valid AddGroupBuyingActivitiesReqVO reqVO) {
        return skdGroupBuyingActivitiesService.startGroupBuying(reqVO);
    }

    /**
     * #0046 缓存团购活动
     * @param reqVO 团购活动缓存请求体
     * @return 返回是否缓存成功
     */
    @ApiOperation("缓存团购活动")
    @PostMapping("/cache")
    public String cacheGroupBuying(GroupBuyingActiviesCacheReqVO reqVO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        log.info("用户id:" + usId);
        log.info("请求缓存数据:" + reqVO);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            dateFormat.parse(reqVO.getStartDate());
            dateFormat.parse(reqVO.getEndDate());
        } catch (ParseException e) {
            e.printStackTrace();
            return ReturnBody.error("日期格式错误!");
        }
        if (!isValidCityDelivery(reqVO.getCityDelivery())) {
            return ReturnBody.error("同城配送数据格式有误!");
        }

        // 打印日志输出 commissionSettings 的值
        log.info("commissionSettings: " + reqVO.getCommissionSettings());
        log.info("volumeRewardSettings: " + reqVO.getVolumeRewardSettings());
        log.info("content" + reqVO.getContent());

        if (StrUtil.isNotBlank(reqVO.getContent())) {
            try {
                isValidContent(reqVO.getContent());
            } catch (IllegalArgumentException e) {
                return ReturnBody.error(e.getMessage());
            }
        }

        if (!isValidBonus(reqVO.getCommissionSettings(), "commissionSettings")){
            return ReturnBody.error("佣金设定数据格式有误!");
        }
        if (!isValidBonus(reqVO.getVolumeRewardSettings(), "volumeRewardSettings")) {
            return ReturnBody.error("达量奖设定数据格式有误!");
        }

        boolean result = redisUtil.cacheGroupBuying(usId, reqVO);
        if (result) {
            return ReturnBody.success("缓存成功!");
        } else {
            return ReturnBody.error("缓存失败!");
        }
    }

    /**
     * #0047 查看缓存的团购活动
     * @return 返回缓存的团购活动内容
     */
    @ApiOperation("查看缓存的团购活动")
    @GetMapping("/check")
    public String checkCache() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        Object respVO = redisUtil.checkCache(usId);
        if (respVO != null) {
            log.info("获取缓存成功!");
            return ReturnBody.success(respVO);
        } else {
            return ReturnBody.error("获取缓存失败!");
        }
    }

    /**
     * #0048 查询团购活动
     * @return 返回团购活动列表
     */
    @ApiOperation("查询团购活动列表")
    @GetMapping
    public String queryGroupBuying() {
        List<GroupBuyingActiviesRespVO> groupBuyingActiviesRespVOList = new ArrayList<>();
        List<SkdGroupBuyingActivities> list = skdGroupBuyingActivitiesService.list();

        list.forEach( i -> {
            GroupBuyingActiviesRespVO groupBuyingActiviesRespVO = new GroupBuyingActiviesRespVO();
            // 获取发起团购活动的用户昵称和头像地址
            UsInfoRespVO userInfo = usInfoService.getAvatarAndNickByUsId(i.getUserId());
            // 获取价格范围
            String priceRange = skdGroupBuyingActivitiesService.getPriceRangeFromGoodsSnapshot(i.getGoodsSnapshot());
            // 获取商品图片地址
            List<String> goodsImages = skdGroupBuyingActivitiesService.getGoodsImagesFromGoodsSnapshot(i.getGoodsSnapshot());
            // 获取商品视频地址
            String goodsVideo = skdGroupBuyingActivitiesService.getGoodsVideoFromGoodsSnapshot(i.getGoodsSnapshot());
            // 获取跟团和浏览人数
            FollowGroupNumAndBrowseNumRespVO followGroupNumAndBrowseNum = skdLeaderInfoService.getFollowGroupNumAndBrowseNumByGroupBuyingActivityId(i.getId());
            log.info("followGroupNumAndBrowseNum" + followGroupNumAndBrowseNum);
            groupBuyingActiviesRespVO
                .setGroupBuyingActivityId(i.getId())
                .setAvatarUrl(userInfo.getAvatar())
                .setNick(userInfo.getNick())
                .setGroupBuyingActivityTitle(i.getTitle())
                .setGroupBuyingActivityPriceRange(priceRange)
                .setGoodsImageUrls(goodsImages)
                .setGoodsVideoUrl(goodsVideo)
                .setFollowGroupNum(followGroupNumAndBrowseNum.getFollowGroupNum())
                .setBrowseNum(followGroupNumAndBrowseNum.getBrowseNum())
                .setIsEnd(i.getIsEnd());
            groupBuyingActiviesRespVOList.add(groupBuyingActiviesRespVO);
        });
        return ReturnBody.success(groupBuyingActiviesRespVOList);
    }

    /**
     * #0049 根据团购活动id查询团购活动详情信息
     * @return 返回是否删除成功信息
     */
    @ApiOperation("根据团购活动id查询团购活动详情信息")
    @GetMapping("get-details")
    public String getById(@NotNull(message = "未提交团购活动id") Long id) {
        SkdGroupBuyingActivities res = skdGroupBuyingActivitiesService.getById(id);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该团购活动不存在!");
        }

        GroupBuyingActiviesDetailRespVO groupBuyingActiviesDetailRespVO = new GroupBuyingActiviesDetailRespVO();

        UsInfoRespVO userInfo = usInfoService.getAvatarAndNickByUsId(res.getUserId());

        FollowGroupNumAndBrowseNumRespVO followGroupNumAndBrowseNumRespVO = skdLeaderInfoService.getFollowGroupNumAndBrowseNumByGroupBuyingActivityId(id);

        groupBuyingActiviesDetailRespVO
                .setAvatarUrl(userInfo.getAvatar())
                .setNick(userInfo.getNick())
                .setFollowGroupNum(followGroupNumAndBrowseNumRespVO.getFollowGroupNum())
                .setBrowseNum(followGroupNumAndBrowseNumRespVO.getBrowseNum())
                .setTitle(res.getTitle())
                .setContent(res.getContent())
                .setGoodsSnapshot(res.getGoodsSnapshot())
                .setCityDelivery(res.getCityDelivery())
                .setPickupPointIds(res.getPickupPointIds())
                .setStartDate(res.getStartDate())
                .setEndDate(res.getEndDate())
                .setIsEnd(res.getIsEnd());

        return ReturnBody.success(groupBuyingActiviesDetailRespVO);
    }

    /**
     * #0050 删除团购活动
     * @return 返回是否删除成功信息
     */
    @ApiOperation("删除团购活动")
    @DeleteMapping
    public String deleteGroupBuying(@NotNull(message = "未提交团购活动id") Long groupBuyingActivityId) {
        if (Objects.isNull(skdGroupBuyingActivitiesService.getById(groupBuyingActivityId)))
        { return ReturnBody.error("该团购活动不存在!"); }
        return skdGroupBuyingActivitiesService.deleteGroupBuying(groupBuyingActivityId);
    }

    /**
     * #0051 修改团购活动
     * @return 返回是否修改成功信息
     */
    @ApiOperation("修改团购活动")
    @PutMapping
    public String modifyGroupBuying(Long groupBuyingActivityId, @Valid AddGroupBuyingActivitiesReqVO reqVO) {
        if (Objects.isNull(skdGroupBuyingActivitiesService.getById(groupBuyingActivityId)))
        { return ReturnBody.error("该团购活动不存在!"); }
        return skdGroupBuyingActivitiesService.modifyGroupBuying(groupBuyingActivityId, reqVO);
    }

    /**
     * #0052 结束团购活动
     * @return 返回是否结束成功信息
     */
    @ApiOperation("结束团购活动")
    @PostMapping("end")
    public String endGroupBuying(@NotNull(message = "未提交团购活动id") Long groupBuyingActivityId){
        if (Objects.isNull(skdLeaderInfoService.getById(groupBuyingActivityId)))
        { return ReturnBody.error("该团购活动不存在, 请检查后重试!"); }
        return skdGroupBuyingActivitiesService.endGroupBuying(groupBuyingActivityId);
    }

    /**
     * #0065 恢复已结束的团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否恢复成功信息
     */
    @ApiOperation("恢复已结束的团购活动")
    @PostMapping("restore")
    public String restoreGroupBuying(@NotNull(message = "未提交团购活动id") Long groupBuyingActivityId) {
        if (Objects.isNull(skdLeaderInfoService.getById(groupBuyingActivityId)))
        { return ReturnBody.error("该团购活动不存在, 请检查后重试!"); }
        return skdGroupBuyingActivitiesService.restoreGroupBuying(groupBuyingActivityId);
    }

    /**
     * #0053 查看已删除的团购活动列表
     * @return 返回已删除的团购活动列表
     */
    @ApiOperation("查看回收站内团购活动")
    @GetMapping("recycle-bin")
    public String checkRecycleBin() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        List<RecycleBinGroupBuyingActivitiesRespVO> res = skdGroupBuyingActivitiesService.checkRecycleBin(usId);
        return ReturnBody.success(res);
    }

    /**
     * #0054 恢复回收站内(已删除)团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否恢复成功
     */
    @ApiOperation("恢复回收站内团购活动")
    @PostMapping("recycle-bin/recover")
    public String recoverRecycleBin(@NotNull(message = "未提交恢复的团购活动id") Long groupBuyingActivityId) {
        SkdGroupBuyingActivities skdGroupBuyingActivity = skdGroupBuyingActivitiesService.selectGroupBuyingActivity(groupBuyingActivityId);

        if (Objects.isNull(skdGroupBuyingActivity))
        { return ReturnBody.error("该团购活动不存在, 请检查后重试!"); }

        return skdGroupBuyingActivitiesService.recoverActivity(groupBuyingActivityId);
    }
}
